package OrderService

import (
	"context"
	"errors"
	"gdshop-admin-go-api/app/entity"
	"gdshop-admin-go-api/app/request/OrderReq"
	"gdshop-admin-go-api/library/response"
	toolsDb "gdshop-admin-go-api/library/tools/db"
	"github.com/gogf/gf/database/gdb"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/util/gconv"
	"time"
)

// 判断订单当前状态是否可以进行某类型操作
func orderIsOption(orderModel *entity.Order, typeStr string) error {
	text := ""
	yunxuStatus := []int{}

	switch typeStr {
	case "price_change": // 改价，订单状态status = 1代付款 时可修改
		text = "改价"
		yunxuStatus = []int{
			1,
		}
		break
	case "back_pay": // 后台付款，订单状态status = 1代付款 时可 后台付款
		text = "后台付款"
		yunxuStatus = []int{
			1,
		}
		break
	case "member_pay": // 会员付款，订单状态status = 1代付款 时可 后台付款
		text = "会员付款"
		yunxuStatus = []int{
			1,
		}
		break
	case "confirm_goods": // 备货，订单状态status = 2 时可 备货
		text = "备货"
		yunxuStatus = []int{
			2,
		}
		break
	case "confirm_order": // 确认收货，订单状态status = 4 时可 确认收货
		text = "后台付款"
		yunxuStatus = []int{
			4,
		}
		break
	case "cancel_goods": // 取消备货，订单状态status = 3 时可 取消备货
		text = "取消备货"
		yunxuStatus = []int{
			3,
		}
		break
	case "send_express": // 发货，订单状态status = 3 时可 发货
		text = "发货"
		yunxuStatus = []int{
			3,
		}
		break
	case "cancel_express": // 取消发货，订单状态status = 3 4 时可 取消发货
		text = "取消发货"
		yunxuStatus = []int{
			3, 4,
		}
		break
	case "close_order": // 确认收货，订单状态status = 4 时可 确认收货
		text = "关闭订单"
		yunxuStatus = []int{
			1, 2, 3,
		}
		break
	}

	for _, item := range yunxuStatus {
		// 只要有一个状态符合，就可以进行操作
		if item == orderModel.Status {
			return nil
		}
	}

	return errors.New("当前订单状态不允许" + text)
}

func SetPriceChange(ctx context.Context, params *OrderReq.SetPriceChange) *response.JsonResponse {
	// 常规判断，只有订单在未付款时才能修改价格
	orderModel := getOrderModel(ctx, params.OrderId)
	if orderModel == nil {
		return response.FailByRequestMessage(nil, "找不到订单")
	}

	err := orderIsOption(orderModel, "price_change")
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}

	res, err := toolsDb.GetUnSafaTable(ctx, "order_price").Where("order_id", params.OrderId).One()
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}

	orderLogData := g.Map{
		"type":     "price_change",
		"order_id": params.OrderId,
		"admin_id": params.AdminId,
		"old_data": "{}",
		"new_data": g.Map{
			"order_id":              params.OrderId,
			"dispatch_price_change": params.DispatchPriceChange,
			"total_price_change":    params.TotalPriceChange,
		},
		"create_at": time.Now().Unix(),
	}
	// 取出子订单全部优惠金额
	totalDiscount, err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "order_sub").Where("order_id", params.OrderId).
		Sum("discount")
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	err = g.DB().Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
		if res.IsEmpty() {
			_, err := tx.Model("order_price").InsertAndGetId(orderLogData["new_data"])
			if err != nil {
				return err
			}
		} else {
			opMap := res.Map()
			orderLogData["old_data"] = g.Map{
				"dispatch_price_change": opMap["dispatch_price_change"],
				"total_price_change":    opMap["total_price_change"],
			}
			_, err := tx.Model("order_price").Where("id", opMap["id"]).Update(orderLogData["new_data"])
			if err != nil {
				return err
			}
		}

		_, err := tx.Model("order_log").InsertAndGetId(orderLogData)
		if err != nil {
			return err
		}
		// 更新订单价格
		orderData := g.Map{
			"total_price":    gdb.Raw("original_total_price-" + gconv.String(totalDiscount) + "+" + params.TotalPriceChange + "+" + params.DispatchPriceChange),
			"dispatch_price": gdb.Raw("original_dispatch_price+" + params.DispatchPriceChange),
		}

		_, err = tx.Model("order").Where("id = ? AND status = 1", params.OrderId).Update(orderData)
		if err != nil {
			return err
		}

		return nil
	})

	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}

	// 修改成功返回价格数据，防止刷新
	/*orderPriceModel := getOrderAndPriceModel(ctx,params.OrderId)

	resultData := g.Map{}
	if orderPriceModel != nil {
		resultData["total_price_change"] = orderPriceModel.TotalPriceChange
		resultData["dispatch_price_change"] = orderPriceModel.DispatchPriceChange
	}

	return response.SuccessByRequestMessageData(nil, "成功",resultData)*/

	return response.SuccessByRequestMessage(nil, "成功")
}
